package com.shareyi.jshop.autocode.tableutil

import com.shareyi.autocode.enumtype.EngineType
import org.apache.commons.io.IOUtils
import org.apache.commons.lang.StringUtils
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
import org.apache.velocity.app.VelocityEngine
import org.omg.CORBA.REBIND;

import java.io.File;

import com.shareyi.jshop.autocode.domain.Template;
import com.shareyi.jshop.autocode.domain.TableModel;
import com.shareyi.fileutil.FileUtil;

import groovy.text.SimpleTemplateEngine;
import groovy.text.TemplateEngine;

class TemplateUtil {
	
	/** Groovy 模板引擎*/
	 TemplateEngine engine;

	/**
	 * VelocityEngine
	 */
	VelocityEngine velocityEngine;


	
	public TemplateUtil()
	{
	   engine=new SimpleTemplateEngine();
		velocityEngine=new VelocityEngine();
		velocityEngine.setProperty(Velocity.INPUT_ENCODING,"utf-8");
		velocityEngine.setProperty(Velocity.OUTPUT_ENCODING,"utf-8");
		velocityEngine.init();
	}

	/**
	 * 渲染模板文件
	 * @param template 模板对象
	 * @param binding 绑定的内容
	 * @return 渲染后的内容
	 */
	String renderTemplate(Template template,binding)
	{
		String tFilePath=template.templateFile;
		File templateFile=new File(tFilePath);

		EngineType engineType=EngineType.getEngineType(template.getEngine());
		String content=null;
		if(engineType==EngineType.GROOVY){
			 templateFile.withReader("utf-8",{reader->
				def tp=engine.createTemplate(reader).make(binding);
				content=tp.toString();
			});
		}else if(engineType==EngineType.VELOCITY){
			StringWriter stringWriter=new StringWriter();
			templateFile.withReader("utf-8" ,{reader->
				String templateContent=IOUtils.toString(reader);
				if(StringUtils.isNotEmpty(templateContent)){
					VelocityContext context = new VelocityContext(binding);
					velocityEngine.evaluate(context,stringWriter, "velocityEngin",templateContent)
				}
				content=stringWriter.toString();
			});
		}
		return content;
	}
	
	/**
	 * 渲染模板内容
	 * @param src 模板内容
	 * @param binding 绑定的内容
	 * @return 渲染后的内容
	 */
	String renderContent(String src,binding)
	{
		def tp=engine.createTemplate(src).make(binding);
		return tp.toString();
	}
}
